<template>
  <div class="app-container">
    <el-card class="test-container">
      <!-- 测试标题和说明 -->
      <div class="test-header">
        <h2>{{ test.title }}</h2>
        <div class="test-info">
          <div>预计用时：{{ test.estimatedTime }}分钟</div>
          <div>总分：{{ test.totalScore }}分</div>
          <div>及格分：{{ test.passScore }}分</div>
        </div>
        <div class="test-description">{{ test.description }}</div>
      </div>

      <!-- 题目列表 -->
      <div class="question-list">
        <div v-for="(question, index) in test.questions" :key="question.id" class="question-item">
          <div class="question-header">
            <span class="question-number">{{ index + 1 }}.</span>
            <span class="question-text">{{ question.questionText }}</span>
            <span class="question-score">({{ question.score }}分)</span>
          </div>
          
          <!-- 选择题 -->
          <div v-if="question.questionType === 1" class="question-options">
            <el-radio-group v-model="answers[question.id]">
              <el-radio 
                v-for="(option, index) in question.options" 
                :key="index" 
                :label="option"
              >
                {{ String.fromCharCode(65 + index) }}. {{ option }}
              </el-radio>
            </el-radio-group>
          </div>
          
          <!-- 多选题 -->
          <div v-else-if="question.questionType === 2" class="question-options">
            <el-checkbox-group v-model="answers[question.id]">
              <el-checkbox 
                v-for="(option, index) in question.options" 
                :key="index" 
                :label="option"
              >
                {{ String.fromCharCode(65 + index) }}. {{ option }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          
          <!-- 量表题 -->
          <div v-else-if="question.questionType === 3" class="question-options">
            <el-radio-group v-model="answers[question.id]">
              <el-radio 
                v-for="(option, index) in question.options" 
                :key="index" 
                :label="String.fromCharCode(65 + index)"
              >
                {{ String.fromCharCode(65 + index) }}. {{ option }}
              </el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="test-actions">
        <el-button @click="$router.push('/test/test-list')">返回列表</el-button>
        <el-button type="primary" @click="submitTest">提交答案</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getTestRecordDetail, getTestDetail, submitTest } from '@/api/psychological-test'
import { getUserInfo } from '@/api/user'

export default {
  name: 'TestPage',
  data() {
    return {
      recordId: null,
      testId: null,
      userId: null,
      startTime: new Date(),
      submitting: false,
      test: {
        title: '',
        description: '',
        estimatedTime: 0,
        totalScore: 0,
        passScore: 0,
        questions: []
      },
      answers: {}
    }
  },
  created() {
    this.recordId = this.$route.query.recordId;
    if (!this.recordId) {
      this.$message.error('无效的测试记录');
      this.$router.push('/test/list');
      return;
    }
    this.getUserInfo();
    this.getTestInfo();
  },
  methods: {
    /** 获取当前用户信息 */
    async getUserInfo() {
      try {
        const response = await getUserInfo();
        if (response.code === 200 && response.data) {
          this.userId = response.data.id;
          console.log('获取用户信息成功:', response.data);
        } else {
          console.error('获取用户信息失败:', response);
          throw new Error(response.message || '获取用户信息失败');
        }
      } catch (error) {
        console.error('获取用户信息异常:', error);
        this.$message.error(error.message || '获取用户信息失败，请重试');
      }
    },
    /** 获取测试信息 */
    async getTestInfo() {
      try {
        // 先获取测试记录
        const recordRes = await getTestRecordDetail(this.recordId)
        console.log('测试记录详情:', recordRes.data)
        
        // 从记录中获取测试ID
        this.testId = recordRes.data.testId
        if (!this.testId) {
          throw new Error('未找到测试ID')
        }

        // 获取测试详情
        const testRes = await getTestDetail(this.testId)
        console.log('测试详情:', testRes.data)
        
        // 确保questions数组存在且每个题目的options都被正确处理
        const questions = testRes.data.questions || []
        questions.forEach(question => {
          // 确保options始终是数组
          if (!Array.isArray(question.options)) {
            question.options = question.questionType !== 3 ? [] : null
          }
        })

        this.test = {
          title: testRes.data.title || '',
          description: testRes.data.description || '',
          estimatedTime: testRes.data.estimatedTime || 0,
          totalScore: testRes.data.totalScore || 0,
          passScore: testRes.data.passScore || 0,
          questions: questions
        }

        // 初始化答案对象
        if (this.test.questions && this.test.questions.length > 0) {
          this.test.questions.forEach(question => {
            if (question.questionType === 2) { // 多选题
              this.answers[question.id] = []
            } else {
              this.answers[question.id] = ''
            }
          })
        } else {
          throw new Error('没有找到测试题目')
        }

        console.log('处理后的测试数据:', this.test)
      } catch (error) {
        console.error('获取测试信息失败:', error)
        this.$message.error(error.message || '获取测试信息失败')
        this.$router.push('/test/test-list')
      }
    },
    /** 提交测试答案 */
    async submitTest() {
      if (!this.validateAnswers()) {
        return;
      }

      if (this.submitting) {
        this.$message.warning('正在提交中，请勿重复操作');
        return;
      }

      this.submitting = true;
      try {
        const processedAnswers = {};
        this.test.questions.forEach(q => {
          if (this.answers[q.id]) {
            processedAnswers[q.id] = this.answers[q.id];
          }
        });

        const data = {
          recordId: this.recordId,
          testId: this.testId,
          userId: this.userId,
          answers: processedAnswers
        };

        const response = await submitTest(data);
        if (response.code === 200) {
          const recordId = response.data;
          await this.$router.push(`/test/result/${recordId}`);
          this.$message({
            type: 'success',
            message: '测试完成！您可以查看初步结果，专业的心理咨询师也会对您的结果进行评估。',
            duration: 5000
          });
        } else {
          this.$message.error(response.message || '提交失败');
        }
      } catch (error) {
        console.error('提交测试失败:', error);
        this.$message.error('提交失败，请重试');
      } finally {
        this.submitting = false;
      }
    },
    validateAnswers() {
      if (!this.userId) {
        this.$message.error('用户信息获取失败，请重新登录')
        return false
      }

      if (!this.testId) {
        this.$message.error('测试ID获取失败，请刷新页面重试')
        return false
      }

      if (!this.test || !this.test.questions || this.test.questions.length === 0) {
        this.$message.error('测试题目获取失败，请刷新页面重试')
        return false
      }

      // 检查是否所有题目都已作答
      const unansweredQuestions = this.test.questions.filter(q => !this.answers[q.id])
      if (unansweredQuestions.length > 0) {
        this.$message.error(`还有${unansweredQuestions.length}道题目未作答，请完成所有题目后再提交`)
        return false
      }

      return true
    }
  }
}
</script>

<style scoped>
.test-container {
  max-width: 800px;
  margin: 0 auto;
}

.test-header {
  text-align: center;
  margin-bottom: 30px;
}

.test-info {
  display: flex;
  justify-content: center;
  gap: 20px;
  color: #666;
  margin: 10px 0;
}

.test-description {
  color: #999;
  margin: 10px 0;
}

.question-list {
  margin: 20px 0;
}

.question-item {
  margin-bottom: 30px;
}

.question-header {
  margin-bottom: 10px;
}

.question-number {
  font-weight: bold;
  margin-right: 10px;
}

.question-score {
  color: #666;
  margin-left: 10px;
}

.question-options {
  margin-left: 25px;
}

.question-options .el-radio {
  margin-right: 30px;
  margin-bottom: 10px;
}

.question-options .el-radio:last-child {
  margin-right: 0;
}

.test-actions {
  text-align: center;
  margin-top: 30px;
}
</style> 